package video.com.utils;

import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import video.com.entity.Video;

import java.io.*;

@Component
public class VideoFormatUtil {

    public static ThreadPool threadPool;

    @Autowired
    public void setThreadPool(ThreadPool threadPool){
        VideoFormatUtil.threadPool = threadPool;
    }

    public static String formatVideo(String videoUrl , String uid) throws IOException{

        int result = -1;
        int pointPos = videoUrl.lastIndexOf(".");

        if(pointPos < 0){
            return null;
        }

        String videoType = videoUrl.substring(pointPos + 1);
        if(videoType.equals("mp4")){
            return makeM3u8(videoUrl, uid);
        }

        String targetVideoUrl = videoUrl.substring(0,pointPos) + "mp4";

        String cmd = String.format("ffmpeg -i %s -c:a copy -c:v libx264 -map 0 %s", videoUrl, targetVideoUrl);

        try {
            Process process = Runtime.getRuntime().exec(cmd);

            dealStream(process);

            try {
                result = process.waitFor();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(result == 0){
            return makeM3u8(targetVideoUrl, uid);
        }
//        -- 视频整体转码ts
//        ffmpeg -y -i bg.mp4  -vcodec copy -acodec copy -vbsf h264_mp4toannexb .\video\music.ts
//                -- ts 文件切片
//        ffmpeg -i .\video\music.ts -c copy -map 0 -f segment -segment_list .\video\music.m3u8 -segment_time 15 .\video\15s_%3d.ts
//        ffmpeg.exe -i  bg.avi -c:v libx264 -s 1280x720 -pix_fmt yuv420p -b:a 63k -b:v 753k -r 18 .\lucene.mp4
//        ffmpeg -i test.avi -c:a copy -c:v libx264 -map 0 test_video.mp4

        return null;
    }

    private static String makeM3u8(String url , String id){

        int pointPos = url.lastIndexOf(".") , result = -1;

        boolean tsExist = false;

        String dir = url.substring(0,pointPos);

        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }

        String tsFile = dir + "/" + id +".ts";
        String m3u8File = dir + "/" + id +".m3u8";

        //m3u8文件已存在
        if(new File(m3u8File).exists()){
            return m3u8File;
        }



        String makeTsFileCmd = String.format("ffmpeg -y -i %s  -vcodec copy -acodec copy -vbsf h264_mp4toannexb %s", url, tsFile);

        try {

            if(!new File(tsFile).exists()){
                Process exec = Runtime.getRuntime().exec(makeTsFileCmd);

                dealStream(exec);
                result = exec.waitFor();
                tsExist = true;
            }

            if(result == 0 || !tsExist){
                StringBuilder str = new StringBuilder();
                str.append("ffmpeg -i ");
                str.append(tsFile);
                str.append(" -c copy -map 0 -f segment -segment_list ");
                str.append(m3u8File);
                str.append(" -segment_time 15 ");
                str.append(dir);
                str.append("\\15s_%3d.ts");
                Process exec = Runtime.getRuntime().exec(str.toString());

                dealStream(exec);

                result = exec.waitFor();

                if(result == 0){
                    return m3u8File;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;

    }

    private static void dealStream(Process process){
        if (process == null) {
            return;
        }

        // 处理InputStream的线程
        threadPool.pool.execute(() -> {
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            try {
                while ((line = in.readLine()) != null) {
                    // logger.info("output: " + line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        threadPool.pool.execute(() -> {
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = null;
            try {
                while ((line = in.readLine()) != null) {
                    // logger.info("output: " + line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
